import { HttpException, HttpStatus, Injectable, NestMiddleware } from "@nestjs/common";
import { Request, Response, NextFunction } from "express";
import { SECRET } from "../config/secret";
import { UserService } from "./user.service";
import * as jwt from 'jsonwebtoken'

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly userService: UserService) {}

  async use(req: Request, res: Response, next: NextFunction) {
    const authHeaders = req.headers.authorization
    if (authHeaders && (authHeaders as string).split(' ')[1]) {
      const token = (authHeaders as string).split(' ')[1]
      const decoded: any = jwt.verify(token, SECRET)
      const user = await this.userService.findById(decoded.id)

      if (!user) {
        throw new HttpException('用户未找到', HttpStatus.UNAUTHORIZED)
      }

      // req.user = user.user
      next()
    } else {
      throw new HttpException('用户未登录', HttpStatus.UNAUTHORIZED)
    }

  }
}
